import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, getRepository, getManager, Not, In, Like, IsNull, UpdateResult, Or } from 'typeorm';
import { Video } from './video.entity';
import DataBase from '../../config/database'
import { Notices } from '../notices/notices.entity';
import { NoticeCheckEnum, NoticeTypeEnum } from '../notices/notices.enum';
import { Questions } from '../questions/questions.entity';
import { question_store_wx_user } from 'src/setting';
import { Answer } from '../answer/answer.entity';
import { EnumRejectReasonType } from '../rejectReason/rejectReason.enum';
import { AnswerIdCard } from '../answerIdCard/answerIdCard.entity';
import { OverseasEnum } from './video.enum';
import { AnswerInfo } from '../answerInfo/answerInfo.entity';
import { InternetCelebrityGroup } from '../internetCelebrityGroup/internetCelebrityGroup.entity';
import { Platform } from '../platform/platform.entity';
import { InternetCelebrity } from '../internetCelebrity/internetCelebrity.entity';
import { EnumInternetCelebrityOverseasEnum } from '../internetCelebrity/internetCelebrity.enum';
import { EnumInternetCelebrityGroupTypeEnum } from '../internetCelebrityGroup/internetCelebrityGroup.enum';
import { TypeEnum } from '../platform/platform.enum';
import utils from 'src/common/utils';
import { RewardSuccess } from '../rewardSuccess/rewardSuccess.entity';
import { Reward } from '../reward/reward.entity';
import { Profit } from '../profit/profit.entity';
import { ProfitRefund } from '../profitRefund/profitRefund.entity';
import { profitRefundStatusEnum } from '../profitRefund/profitRefund.enum';
import { EnumProfitPostAnswer, profitEnum, profitTypeEnum } from '../profit/profit.enum';
import { LikeVideo } from '../likeVideo/likeVideo.entity';
import { RejectReason } from '../rejectReason/rejectReason.entity';
import { payStatusEnum } from '../reward/reward.enum';
import { MultiImg } from '../multiImg/multiImg.entity';
import { WXAPI } from '../../common/wx_api'
import { getOtherNetwork_ic_info } from 'src/common/sql/video';
import { WsStartGateway } from '../ws/ws.gateway';
import { VideoBackUp } from '../videoBackup/videoBackup.entity';
import { RedisCacheService } from '../redisCache/redisCache.service';
import { VideoAbroad } from '../videoAbroad/videoAbroad.entity';
import { AnswerAbroad } from '../answerAbroad/answerAbroad.entity';
import { MultiImgAbroad } from '../multiImgAbroad/multiImgAbroad.entity';
let WXAPIOBJ = new WXAPI()


@Injectable()
export class VideoServiceManager {
  constructor(
    @InjectRepository(Video)
    private videoRepository: Repository<Video>,
    @InjectRepository(Questions)
    private questionsIcRepository: Repository<Questions>,
    @InjectRepository(Answer)
    private answerRepository: Repository<Answer>,
    @InjectRepository(Notices)
    private noticesRepository: Repository<Notices>,
    @InjectRepository(AnswerIdCard)
    private answerIdCardRespository: Repository<AnswerIdCard>,
    @InjectRepository(AnswerInfo)
    private answerInfoRespository: Repository<AnswerInfo>,
    @InjectRepository(InternetCelebrityGroup)
    private internetCelebrityGroupRespository: Repository<InternetCelebrityGroup>,
    @InjectRepository(Platform)
    private platformRespository: Repository<Platform>,
    @InjectRepository(InternetCelebrity)
    private internetCelebrityRespository: Repository<InternetCelebrity>,
    @InjectRepository(RewardSuccess)
    private rewardSuccessRespository: Repository<RewardSuccess>,
    @InjectRepository(Reward)
    private rewardRespository: Repository<Reward>,
    @InjectRepository(Profit)
    private profitRespository: Repository<Profit>,
    @InjectRepository(ProfitRefund)
    private profitRefundRespository: Repository<ProfitRefund>,
    @InjectRepository(LikeVideo)
    private likeVideoRespository: Repository<LikeVideo>,
    @InjectRepository(RejectReason)
    private rejectReasonRespository: Repository<RejectReason>,
    @InjectRepository(MultiImg)
    private multiImgRespository: Repository<MultiImg>,
    @InjectRepository(ProfitRefund)
    private profitRefundRepository: Repository<ProfitRefund>,
    private readonly wsStartGateway: WsStartGateway,
    @InjectRepository(VideoBackUp)
    private videoBackUpRepository: Repository<VideoBackUp>,
    @InjectRepository(VideoAbroad)
    private videoAbroadRepository: Repository<VideoAbroad>,
    @InjectRepository(AnswerAbroad)
    private answerAbroadRepository: Repository<AnswerAbroad>,
    @InjectRepository(MultiImgAbroad)
    private multiImgAbroadRepository: Repository<MultiImgAbroad>,
    private readonly redisCacheService: RedisCacheService,


  ) { }

  async findQuestionNotAnswer(skip: number, take: number, video_id?: number, selectType?: string): Promise<any> {
    let sql = ``
    let params = [skip, take]
    let totalParams = []
    if (video_id) {
      sql = ` and video.id = ?`
      params.splice(0, 0, video_id)
      totalParams.push(video_id)
    }
    let dataList = []
    let total = 0
    if (selectType === 'all') {
      dataList = await this.videoRepository.query(`
        select distinct video.id, video.video_id,video.check, video.video_url, video.video_url_source,video.video_cover,video.type,
        (
          select v.id from video as v
          inner join platform on platform.ic_group = v.ic_group
          inner join internet_celebrity_group on internet_celebrity_group.id = v.ic_group
          where v.id = video.id and internet_celebrity_group.type = 0
            and platform.platform in (select setting.value from setting where setting.key = 'level3')
            and internet_celebrity_group.delete_tag = 0
            and (
              v.overseas = 3
              or (v.original = 0 and v.type = 0)
            )
            
          limit 0,1
        ) as otherNetwork_ic_info,
        video.is_home,
        video.in_ic
        from video 
        where video.original = 0 and 
        (
          (video.source = 0 and video.check_text = 1)
          OR
          (
            video.source = 2 and video.check = 1 and video.id in (
              select answer.video_id from answer
              inner join answer_info on answer_info.answer_id = answer.id
              where answer.check is null
            ) and video.ic_group is null
          )
        )
        ${sql}
        order by video.id asc
        limit ?,?
      `, params)

      //查询视频关联的网红
      let videoRelaIcWhere = []
      dataList.map(e => {
        if (e.video_url_source) {
          e.video_url = e.video_url_source
        }
        if (e.select_type) {
          e.select_type = 'wait_check'
        }
        videoRelaIcWhere.push(`video.id = ?`)
      })

      if (videoRelaIcWhere.length > 0) {
        let videoRelaIc = await this.videoRepository.query(`
          select distinct platform.platform,internet_celebrity.name as ic_name, internet_celebrity.account, internet_celebrity.img, internet_celebrity.avatar_img,video.id
          from internet_celebrity
          inner join platform on platform.id = internet_celebrity.platform
          inner join video on video.ic_group = internet_celebrity.ic_group
          where (${videoRelaIcWhere.join(' or ')}) and platform.platform is not null and platform.platform != ''
        `, dataList.map(e => e.id))

        videoRelaIc.map((e, index) => {
          let findVideo = dataList.find(c => c.id == e.id)
          if (findVideo) {
            if (!findVideo.ic_info) {
              findVideo.ic_info = e
            } else {
              let addVideo = JSON.parse(JSON.stringify(findVideo))
              addVideo.ic_info = e
              dataList.push(addVideo)
            }
          }
        })
      }

      total = await this.videoRepository.query(`
        select count(1) as total from video
        where video.original = 0 and 
        (
          (video.source = 0 and video.check_text = 1)
          OR
          (
            video.source = 2 and video.check = 1 and video.id in (
              select answer.video_id from answer
              inner join answer_info on answer_info.answer_id = answer.id
              where answer.check is null
            ) and video.ic_group is null
          )
        )
        ${sql}
      `, totalParams)
    } else {
      dataList = await this.videoRepository.query(`
        select distinct video.id, video.video_id, video.check, video.video_url, video.video_url_source,video.video_cover,video.type,
        (
          select v.id from video as v
          inner join platform on platform.ic_group = v.ic_group
          inner join internet_celebrity_group on internet_celebrity_group.id = v.ic_group
          where v.id = video.id and internet_celebrity_group.type = 0
            and platform.platform in (select setting.value from setting where setting.key = 'level3')
            and internet_celebrity_group.delete_tag = 0
            and (
              v.overseas = 3
              or (v.original = 0 and v.type = 0)
            )
            
          limit 0,1
        ) as otherNetwork_ic_info,
        video.is_home,
        video.in_ic
        from video
        inner join answer on answer.video_id = video.id
        inner join answer_info on answer_info.answer_id = answer.id
        where video.original = 0 and video.ic_group is null and (
          (
            video.source = 0 and video.check_text = 1) or video.source = 2
          ) and answer.check is null
          ${sql}
        order by video.id asc
        limit ?,?
      `, params)

      total = await this.videoRepository.query(`
        select count(1) as total from video
        inner join answer on answer.video_id = video.id
        inner join answer_info on answer_info.answer_id = answer.id
        where video.original = 0 and video.ic_group is null and (
          (
            video.source = 0 and video.check_text = 1) or video.source = 2
          ) and answer.check is null
        ${sql}
      `, totalParams)
    }
    return {
      dataList: dataList,
      total: Number(total[0]?.total || 0)
    }
  }


  getIDCard() {
    let id = ''
    let loop = async () => {
      id = utils.randomNumberID(7)
      if (await this.internetCelebrityGroupRespository.findOne({ where: { id_card: id } })) {
        loop()
      }
    }
    loop()
    return id
  }

  /**
   * 视频/图片审核
   * @param id 
   * @returns 
   */
  async acceptWorks(id: number): Promise<any> {
    //查询视频详情
    let findVideo = await this.videoRepository.findOne({ where: { id: id } })
    if (!findVideo) {
      return '视频不存在'
    }
    let db: DataBase = new DataBase()
    let connection = await db.getConnection()
    const queryRunner = connection.createQueryRunner()
    await queryRunner.connect()
    // 开始事务
    await queryRunner.startTransaction()
    try {
      let updateVideoParams: any = { check: 1, check_time: new Date(), check_text: 1, check_text_time: new Date(), is_home: 1 }
      //检测是否是未认证作品，
      //如果是，并且没有关联网红，则自动创建网红
      if (findVideo.original == 1 && findVideo.overseas == OverseasEnum.virtual && !findVideo.ic_group) {
        throw new Error('没有关联网红')
      }
      //未认证作品审核通过后默认不进入网红主页
      if (findVideo.original == 1 && findVideo.overseas == OverseasEnum.virtual) {
        updateVideoParams.in_ic = 0
      }

      //添加通知
      let notice = new Notices()
      notice.create_time = new Date()
      notice.video_id = id
      notice.wx_user = findVideo.wx_user
      notice.check = 1
      //提问
      if (findVideo.original == 0) {
        notice.type = NoticeTypeEnum.question_accept
        //修改作品所属为提问仓库用户
        if (findVideo.wx_user !== question_store_wx_user) {
          updateVideoParams.wx_user = question_store_wx_user
          updateVideoParams.wx_user_source = findVideo.wx_user
          //添加视频原有用户为同提问
          let question = new Questions()
          question.video_id = findVideo.id
          question.create_time = new Date()
          question.wx_user = findVideo.wx_user
          await this.questionsIcRepository.createQueryBuilder(null, queryRunner).insert().into(Questions).values(question).execute()
        }
      } else if (findVideo.original == 1) {//作品
        notice.type = NoticeTypeEnum.works_accept
      }
      //添加通知
      await queryRunner.manager.save(notice)
      //修改审核状态
      await this.videoRepository.createQueryBuilder(null, queryRunner).update(updateVideoParams).where({ id: id }).execute()

      await queryRunner.commitTransaction()
      await queryRunner.release();
      //添加通知
      this.wsStartGateway.postUpdateNotice(notice.wx_user)
      //更新视频数据
      this.wsStartGateway.postUpdateVideo(findVideo.id)
    } catch (err) {
      // 有错误做出回滚更改
      await queryRunner.rollbackTransaction()
      await queryRunner.release();
      return err
    }
  }

  async rejectWorks(id: number, reject_reason: number): Promise<any> {
    //查询视频详情
    let findVideo = await this.videoRepository.findOne({ where: { id: id } })
    if (!findVideo) {
      return '视频不存在'
    }
    let db: DataBase = new DataBase()
    let connection = await db.getConnection()
    const queryRunner = connection.createQueryRunner()
    await queryRunner.connect()
    // 开始事务
    await queryRunner.startTransaction()
    try {
      //添加通知
      let notice = new Notices()
      notice.create_time = new Date()
      notice.video_id = id
      notice.wx_user = findVideo.wx_user
      notice.check = 0
      notice.reject_reason = reject_reason
      //提问
      if (findVideo.original == 0) {
        notice.type = NoticeTypeEnum.question_reject
      } else if (findVideo.original == 1) {//作品
        notice.type = NoticeTypeEnum.works_reject
      }
      //添加通知
      await queryRunner.manager.save(notice)
      //修改审核状态
      await this.videoRepository.createQueryBuilder(null, queryRunner).update({
        check: 0, check_time: new Date(), check_text: 0, check_text_time: new Date(),
        reject_reason: reject_reason
      }).where({ id: id }).execute()
      await queryRunner.commitTransaction()
      await queryRunner.release();

      //添加通知
      this.wsStartGateway.postUpdateNotice(notice.wx_user)
      //更新视频数据
      this.wsStartGateway.postUpdateVideo(findVideo.id)
    } catch (err) {
      // 有错误做出回滚更改
      await queryRunner.rollbackTransaction()
      await queryRunner.release();
      return err
    }
  }

  /**
   * 提问视频指定网红
   * @param video_id 
   * @param ic_group 
   * @returns 
   */
  async changeIcGroup_question(video_id: number, ic_group: number) {
    //查询视频详情
    let findVideo = await this.videoRepository.findOne({ where: { id: video_id } })
    if (!findVideo) {
      return '视频不存在'
    }
    //查询已找到答案的驳回原因id
    let findFindIsFind = await this.answerRepository.query(`
      select reject_reason.id from reject_reason
      where reject_reason.key = 'answer_is_find'
    `, [])
    if (findFindIsFind.length === 0) {
      throw new Error('找不到驳回原因 answer_is_find，请添加')
    }
    let reject_reason = findFindIsFind[0].id

    //查询所有回答当前视频，并且还未审核的答案
    let notCheckAnswerList = await this.answerRepository.query(`
      select * from answer
      where answer.check is null and answer.video_id = ?
    `, [video_id])

    //查询审核通过的答案
    let findAuthorAnswer = await this.answerRepository.findOne({ where: { video_id: video_id, check: 1, delete_tag: 0 } })

    let db: DataBase = new DataBase()
    let connection = await db.getConnection()
    const queryRunner = connection.createQueryRunner()
    await queryRunner.connect()
    // 开始事务
    await queryRunner.startTransaction()
    try {
      //修改视频的网红
      await this.videoRepository.createQueryBuilder(null, queryRunner).update({ ic_group: ic_group, check: 1 }).where({ id: video_id }).execute()
      //拒绝其他回答者的答案
      await this.answerRepository.createQueryBuilder(null, queryRunner).update({ check: 0, check_time: new Date(), reject_reason: reject_reason, update_time: new Date() }).where({ video_id: video_id, check: IsNull() }).execute()

      let noticeList = []
      //通知当前视频其他未审核的人
      notCheckAnswerList.map(e => {
        let notice = new Notices()
        notice.create_time = new Date()
        notice.video_id = video_id
        notice.wx_user = e.wx_user
        notice.check = NoticeCheckEnum.no
        notice.type = NoticeTypeEnum.answer_reject
        notice.answer_id = e.id
        notice.reject_reason = reject_reason
        noticeList.push(notice)
      })

      let answer_id, answer_author
      if (!findAuthorAnswer) {
        //修改当前视频的作者为受益人
        let addAnswer = new Answer()
        addAnswer.video_id = video_id
        addAnswer.wx_user = question_store_wx_user
        addAnswer.create_time = new Date()
        addAnswer.check = 1
        addAnswer.check_time = new Date()
        addAnswer.type = 0
        //获取当前用户的回答id
        let findAnswerIdCard = await this.answerIdCardRespository.findOne({ where: { wx_user: addAnswer.wx_user, video_id: video_id } })
        if (findAnswerIdCard) {
          addAnswer.id_card = findAnswerIdCard.id_card
        } else {
          let answerIdCard = new AnswerIdCard()
          answerIdCard.wx_user = addAnswer.wx_user
          answerIdCard.video_id = video_id
          answerIdCard.id_card = addAnswer.id_card
          //查找最大id_card
          let maxIdCard = await this.answerIdCardRespository.query(`select max(id_card) as id_card from answer_id_card where wx_user = ?`, [addAnswer.wx_user])
          if (maxIdCard.length > 0) {
            answerIdCard.id_card = (maxIdCard[0].id_card || 0) + 1
          }
          await this.answerIdCardRespository.createQueryBuilder(null, queryRunner).insert().into(AnswerIdCard).values(answerIdCard).execute()
          addAnswer.id_card = answerIdCard.id_card
        }
        let addAnswerResult = await this.answerRepository.createQueryBuilder(null, queryRunner).insert().into(Answer).values(addAnswer).execute()
        answer_id = addAnswerResult.identifiers[0].id
        answer_author = addAnswer.wx_user
      } else {
        await this.answerRepository.createQueryBuilder(null, queryRunner).update({ update_time: new Date() }).where({ id: findAuthorAnswer.id }).execute()
        answer_id = findAuthorAnswer.id
        answer_author = findAuthorAnswer.wx_user
      }
      //给同提问的人发答案
      await this.questionsIcRepository.createQueryBuilder(null, queryRunner).update({ answer_time: new Date(), post_answer: 1 }).where({ video_id: video_id, answer_time: IsNull() }).execute()
      await this.rewardRespository.createQueryBuilder(null, queryRunner).update({ pay_status: payStatusEnum.used }).where({ video_id: video_id, pay_status: payStatusEnum.success }).execute()
      //给悬赏的人发答案
      //查询已经悬赏的用户
      let findRewardSuccessList = await this.rewardSuccessRespository.find({ where: { video_id: video_id } })
      let profitList = []
      findRewardSuccessList.map(e => {
        //添加收益表
        let profit = new Profit()
        profit.answer_id = answer_id
        profit.author_wx_user = answer_author
        profit.use_wx_user = e.wx_user
        profit.status = profitEnum.entry
        profit.create_time = new Date()
        profit.update_time = new Date()
        profit.unit_price = e.unit_price - e.service_charge
        profit.service_charge = e.service_charge
        profit.type = profitTypeEnum.consume
        profitList.push(profit)
      })
      if (profitList.length > 0) {
        await this.profitRespository.createQueryBuilder(null, queryRunner).insert().into(Profit).values(profitList).execute()
      }

      //给同提问发通知
      let findQuestionsList: Questions[] = await this.questionsIcRepository.query(`
        select * from questions
        where questions.post_answer = 1 and questions.video_id = ?
      `, [video_id])
      let nowTime = new Date()
      findQuestionsList.map(e => {
        let notice = new Notices()
        notice.create_time = nowTime
        notice.video_id = video_id
        notice.wx_user = e.wx_user
        notice.check = NoticeCheckEnum.yes
        notice.type = NoticeTypeEnum.question_is_answer
        notice.answer_id = answer_id
        noticeList.push(notice)
      })

      //保存通知
      if (noticeList.length > 0) {
        await this.noticesRepository.createQueryBuilder(null, queryRunner)
          .insert()
          .into(Notices)
          .values(noticeList)
          .execute()
      }

      await queryRunner.commitTransaction()
      await queryRunner.release();
    } catch (err) {
      // 有错误做出回滚更改
      await queryRunner.rollbackTransaction()
      await queryRunner.release();
      return err
    }
  }

  clearIcGroup(video_id: number): Promise<any> {
    return this.videoRepository.update({ id: video_id }, { ic_group: null })
  }


  async copyToAll(video_id: number) {
    //查询视频
    let findVideo = await this.videoRepository.findOne({ where: { id: video_id } })
    findVideo.isreward = 0
    findVideo.check = 0
    findVideo.check_text = null
    findVideo.create_time = new Date()
    findVideo.update_time = new Date()
    findVideo.source = 2
    findVideo.original = 0
    findVideo.ic_group = null
    findVideo.overseas = 0
    findVideo.wx_user = 'oGCIM6xIWkOgZ_QxejB3TrMl1-MQ'
    delete findVideo.id
    if (findVideo.video_url_source) {
      findVideo.video_url = findVideo.video_url_source
      delete findVideo.video_url_source
    }
    return await this.videoRepository.insert(findVideo)
  }

  /**
   * 添加通知
   */
  addNotice(video_id, wx_user, noticeType): Notices {
    //添加删除视频通知
    let notice = new Notices()
    notice.video_id = video_id
    notice.wx_user = wx_user
    notice.create_time = new Date()
    notice.type = noticeType
    notice.check = 1
    return notice
  }

  async removeManager(id: number): Promise<any> {
    //查询视频详情
    let findVideo = await this.videoRepository.findOne({ where: { id: id } })
    if (!findVideo) {
      return '视频不存在'
    }

    //查询视频有没有过退款
    // let findIsRefund = await this.videoRepository.query(`
    //   select * from profit_refund
    //   inner join answer on answer.id = profit_refund.answer_id
    //   where answer.check = 1 and answer.video_id = ?
    // `,[id])
    // if(findIsRefund.length === 0){
    //   return '没有人退款，不可删除！'
    // }
    //查询视频的答案
    let findAnswer = await this.answerRepository.findOne({ where: { video_id: id, check: 1, delete_tag: 0 } })
    // if(!findAnswer){
    //   return '没有答案'
    // }
    //查询所有付款的人
    let findProfitList = await this.profitRespository.query(`
      select profit.* from profit
      inner join answer on answer.id = profit.answer_id
      where answer.check = 1 and answer.video_id = ?
    `, [findVideo.id])
    //查询所有悬赏
    let findRewardSuccessList = await this.rewardSuccessRespository.find({ where: { video_id: findVideo.id } })

    //查询所有回答
    let findAnswerInfoList = await this.answerInfoRespository.query(`
      select answer_info.id from answer_info
      inner join answer on answer.id = answer_info.id
      where answer.video_id = ?
    `, [findVideo.id])

    //查询删除视频的通知信息id
    // let deleteWorkReason = await this.rejectReasonRespository.findOne({where:{key: 'delete_work'}})

    let db: DataBase = new DataBase()
    let connection = await db.getConnection()
    const queryRunner = connection.createQueryRunner()
    await queryRunner.connect()
    // 开始事务
    await queryRunner.startTransaction()
    try {
      //修改所有人的同提问
      await this.questionsIcRepository.createQueryBuilder(null, queryRunner)
        .update({ answer_time: null, post_answer: 0 })
        .where({ video_id: id })
        .execute()
      //退还所有人的悬赏
      await this.rewardSuccessRespository.createQueryBuilder(null, queryRunner)
        .delete()
        .where({ video_id: findVideo.id })
        .execute()
      await this.rewardRespository.createQueryBuilder(null, queryRunner)
        .update({ pay_status: payStatusEnum.reject })
        .where({ video_id: findVideo.id })
        .execute()
      if (findAnswer) {
        //修改所有人的付款为已退款
        await this.profitRespository.createQueryBuilder(null, queryRunner)
          .delete()
          .where({ answer_id: findAnswer.id, status: profitEnum.entry })
          .execute()
      }

      //添加收益退款记录
      if (findProfitList.length > 0) {
        let profitRefundList = []
        findProfitList.map(findProfit => {
          let profitRefund = new ProfitRefund()
          profitRefund.answer_id = findProfit.answer_id
          profitRefund.author_wx_user = findProfit.author_wx_user
          profitRefund.use_wx_user = findProfit.use_wx_user
          profitRefund.status = profitRefundStatusEnum.refoundSuccess
          profitRefund.notes = findProfit.notes
          profitRefund.service_charge = findProfit.service_charge
          profitRefund.unit_price = findProfit.unit_price
          profitRefund.type = findProfit.type
          profitRefund.update_time = findProfit.update_time
          profitRefund.create_time = findProfit.create_time
          profitRefund.delivery_time = findProfit.create_time
          profitRefundList.push(profitRefund)
        })
        await this.profitRefundRespository.createQueryBuilder(null, queryRunner)
          .insert()
          .into(ProfitRefund)
          .values(profitRefundList)
          .execute()
      }

      //删除所有人的回答
      await this.answerRepository.createQueryBuilder(null, queryRunner)
        .delete()
        .where({ video_id: findVideo.id })
        .execute()
      await this.answerInfoRespository.createQueryBuilder(null, queryRunner)
        .delete()
        .whereInIds(findAnswerInfoList.map(e => e.id))
        .execute()
      //删除所有人的同提问
      await this.questionsIcRepository.createQueryBuilder(null, queryRunner)
        .delete()
        .where({ video_id: findVideo.id })
        .execute()
      //删除所有人收藏
      await this.likeVideoRespository.createQueryBuilder(null, queryRunner)
        .delete()
        .where({ video_id: findVideo.id })
        .execute()
      //删除多图
      await this.multiImgRespository.createQueryBuilder(null, queryRunner)
        .delete()
        .where({ video_id: findVideo.id })
        .execute()


      //添加删除视频通知
      // let notice = this.addNotice(findVideo.id, findVideo.wx_user, NoticeTypeEnum.works_delete)
      // await this.noticesRepository.createQueryBuilder(null, queryRunner)
      //   .insert()
      //   .into(Notices)
      //   .values(notice)
      //   .execute()

      //删除视频
      await this.videoRepository.createQueryBuilder(null, queryRunner)
        .delete()
        .where({ id: findVideo.id })
        .execute()
      await queryRunner.commitTransaction()
      await queryRunner.release();

      let clearWxUsers = [...new Set([...findRewardSuccessList.map(e => e.wx_user), ...findProfitList.map(e => e.use_wx_user)])]
      let len = clearWxUsers.length
      let loop = async () => {
        len--
        //清空所有消费用户的钱包缓存
        await WXAPIOBJ.clearPayWallet(clearWxUsers[len])
        if (len > 0) {
          await loop()
        }
      }
      if (len > 0) {
        await loop()
      }
    } catch (err) {
      // 有错误做出回滚更改
      await queryRunner.rollbackTransaction()
      await queryRunner.release();
      return err
    }
  }

  async questionWaitIsHomeList(video_id: number, skip: number, take: number) {
    let dataList: any = [], total: any = 0
    if (video_id) {
      dataList = await this.videoRepository.query(`
        select *
        from video
        where video.original = 0 and video.id = ? and (video.check_text = 1 or (video.source = 2 and video.check = 1)) and video.ic_group is not null
      `, [video_id])
      total = dataList.length
    } else {
      dataList = await this.videoRepository.query(`
        select *
        from video
        where video.original = 0 and video.ic_group is not null and (
          video.check_text = 1 or (video.source = 2 and video.check = 1)
        )
        order by id asc
        limit ?,?
      `, [skip, take])
      total = await this.videoRepository.query(`
        select count(1) as total from video
        where video.original = 0 and video.ic_group is not null and (
          video.check_text = 1 or (video.source = 2 and video.check = 1)
        )
      `, [])
      total = total[0].total
    }
    if (dataList.length > 0) {
      //查询视频关联的网红
      let videoRelaIcWhere = []
      dataList.map(e => {
        if (e.video_url_source) {
          e.video_url = e.video_url_source
        }
        videoRelaIcWhere.push(`video.id = ?`)
      })

      let videoRelaIc = await this.videoRepository.query(`
        select distinct platform.platform,internet_celebrity.name as ic_name, internet_celebrity.account, internet_celebrity.img, internet_celebrity.avatar_img,video.id
        from internet_celebrity
        inner join platform on platform.id = internet_celebrity.platform
        inner join video on video.ic_group = internet_celebrity.ic_group
        where (${videoRelaIcWhere.join(' or ')}) and platform.platform is not null and platform.platform != ''
      `, dataList.map(e => e.id))

      videoRelaIc.map((e, index) => {
        let findVideo = dataList.find(c => c.id == e.id)
        if (findVideo) {
          if (!findVideo.ic_info) {
            findVideo.ic_info = e
          } else {
            let addVideo = JSON.parse(JSON.stringify(findVideo))
            addVideo.ic_info = e
            dataList.push(addVideo)
          }
        }
      })
    }
    return { total, data: dataList }
  }

  async resetQuestion(video_id: number) {
    //查询回答错误id
    let rejectReason = await this.rejectReasonRespository.findOne({ where: { type: EnumRejectReasonType.answer, key: 'answer_error' } })
    if (!rejectReason) {
      return '缺少拒绝原因，请联系管理员添加'
    }
    let rejectReasonRefund = await this.rejectReasonRespository.findOne({ where: { type: EnumRejectReasonType.refund, key: 'answer_error_is_refund' } })
    if (!rejectReasonRefund) {
      return '缺少退款拒绝原因，请联系管理员添加'
    }
    //查询已通过的答案
    let findAnswer: Answer = await this.answerRepository.findOne({ where: { video_id: video_id, check: 1 } })
    //查询已付款的列表
    let findProfitList: Profit[] = await this.profitRespository.find({ where: { answer_id: findAnswer.id } })

    let db: DataBase = new DataBase()
    let connection = await db.getConnection()
    const queryRunner = connection.createQueryRunner()
    await queryRunner.connect()
    // 开始事务
    await queryRunner.startTransaction()
    try {
      //修改视频为没答案视频
      await this.videoRepository.createQueryBuilder(null, queryRunner).update({ ic_group: null, update_time: new Date() }).where({ id: video_id }).execute()
      //拒绝已通过的答案
      await this.answerRepository.createQueryBuilder(null, queryRunner).update({ check: 0, reject_reason: rejectReason.id, update_time: new Date() }).where({ video_id: video_id, check: 1 }).execute()
      //清空同提问时间
      await this.questionsIcRepository.createQueryBuilder(null, queryRunner)
        .update({ answer_time: null, post_answer: 0 })
        .where({ video_id: video_id })
        .execute()
      //删除悬赏
      await this.rewardSuccessRespository.createQueryBuilder(null, queryRunner)
        .delete()
        .where({ video_id: video_id })
        .execute()
      await this.rewardRespository.createQueryBuilder(null, queryRunner)
        .update({ pay_status: payStatusEnum.reject })
        .where({ video_id: video_id })
        .execute()
      //给所有已消费的用户退款
      await this.profitRespository.createQueryBuilder(null, queryRunner)
        .delete()
        .where({ answer_id: findAnswer.id })
        .execute()

      let noticesList: Notices[] = []
      let findProfitRefundList: ProfitRefund[] = []
      findProfitList.map(findProfit => {
        let profitRefund = new ProfitRefund()
        profitRefund.answer_id = findProfit.answer_id
        profitRefund.author_wx_user = findProfit.author_wx_user
        profitRefund.use_wx_user = findProfit.use_wx_user
        profitRefund.status = profitRefundStatusEnum.refoundSuccess
        profitRefund.notes = findProfit.notes
        profitRefund.service_charge = findProfit.service_charge
        profitRefund.unit_price = findProfit.unit_price
        profitRefund.type = findProfit.type
        profitRefund.update_time = findProfit.update_time
        profitRefund.create_time = findProfit.create_time
        profitRefund.delivery_time = findProfit.create_time
        findProfitRefundList.push(profitRefund)


        //通知消费用户退款成功
        let notices = new Notices()
        notices.video_id = video_id
        notices.answer_id = findProfit.id
        notices.wx_user = findProfit.use_wx_user
        notices.create_time = new Date()
        notices.type = NoticeTypeEnum.refund_answer_is_error_accept
        notices.check = NoticeCheckEnum.yes
        notices.reject_reason = rejectReasonRefund.id
        noticesList.push(notices)
      })
      if (findProfitRefundList.length > 0) {
        await this.profitRefundRepository.createQueryBuilder(null, queryRunner)
          .insert()
          .into(ProfitRefund)
          .values(findProfitRefundList)
          .execute()

        findProfitRefundList.map(profitRefund => {
          WXAPIOBJ.clearPayWallet(profitRefund.use_wx_user)
        })

      }
      //拒绝回答者的通知
      let notices = new Notices()
      notices.video_id = findAnswer.video_id
      notices.answer_id = findAnswer.id
      notices.wx_user = findAnswer.wx_user
      notices.create_time = new Date()
      notices.type = NoticeTypeEnum.answer_reject
      notices.check = NoticeCheckEnum.yes
      notices.reject_reason = rejectReason.id
      noticesList.push(notices)
      if (noticesList.length > 0) {
        await this.noticesRepository.createQueryBuilder(null, queryRunner).insert().into(Notices).values(noticesList).execute()
      }

      await queryRunner.commitTransaction()
      await queryRunner.release();
    } catch (err) {
      // 有错误做出回滚更改
      await queryRunner.rollbackTransaction()
      await queryRunner.release();
      return err
    }
  }

  /**
   * 下架网红所有视频
   * @param ic_group 
   * @returns 
   */
  checkNoAll(ic_group: number) {
    return this.videoRepository.update({ ic_group: ic_group }, { check: 0 })
  }

  async replaceVideoCover(id: number, video_id: string, img: string, shareCover: string) {
    //查询是否有备份数据
    let findVideoBack = await this.videoBackUpRepository.findOne({ where: { video_id: id } })
    let db: DataBase = new DataBase()
    let connection = await db.getConnection()
    const queryRunner = connection.createQueryRunner()
    await queryRunner.connect()
    // 开始事务
    await queryRunner.startTransaction()
    try {
      let coverUrl = await utils.ReplaceVideoCover(video_id, img)
      //修改数据库
      await this.videoRepository.createQueryBuilder(null, queryRunner)
        .update({ video_cover: coverUrl, share_cover: shareCover })
        .where({ id: id })
        .execute()

      //修改备份视频
      if (findVideoBack) {
        let coverUrlBackUp = await utils.ReplaceVideoCover_BackUp(findVideoBack.video_id_new, img)
        let coverUrlBackUp_Hls = await utils.ReplaceVideoCover_BackUp(findVideoBack.hls_video_id_new, img)

        //修改数据库
        await this.videoBackUpRepository.createQueryBuilder(null, queryRunner)
          .update({ video_cover_new: coverUrlBackUp, hls_video_cover_new: coverUrlBackUp_Hls, video_cover_old: coverUrl })
          .where({ video_id: findVideoBack.video_id })
          .execute()
      }
      await queryRunner.commitTransaction()
      await queryRunner.release();
      //删除缓存
      await this.redisCacheService.del(`videos:${id}:basic`)
    } catch (err) {
      // 有错误做出回滚更改
      await queryRunner.rollbackTransaction()
      await queryRunner.release();
      return err
    }
  }

  async updateInLevel3(video_id, in_level3) {
    let question = await this.questionsIcRepository.count({ where: { video_id: video_id } })
    if (question > 0) {
      return '有同提问数据，不能修改'
    }
    let answer = await this.answerRepository.query(`
      select count(1) as total from answer
      where answer.video_id = ? and (answer.check = 0 or answer.check is null)  
    `, [video_id])
    if (Number(answer[0].total || 0) > 0) {
      return '有回答数据，不能修改'
    }
    let db: DataBase = new DataBase()
    let connection = await db.getConnection()
    const queryRunner = connection.createQueryRunner()
    await queryRunner.connect()
    // 开始事务
    await queryRunner.startTransaction()
    try {
      let updateParams: any = { in_level3: in_level3 }
      if (in_level3 == 1) {
        updateParams.basic_reward = 0
        updateParams.basic_questions = 0
      } else {
        let rand = Math.random() * 100
        if (rand <= 90) {
          // 使用示例
          const arr = [1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000];
          const sampleSize = 1;
          const sampled = utils.sample(arr, sampleSize);
          if (sampled.length > 0) {
            rand = sampled[0]
          } else {
            rand = undefined
          }
        } else {
          rand = 10000
        }
        if (rand !== undefined) {
          updateParams.basic_questions = rand
          let sj = parseInt(utils.getRandomNumber(14, 33))
          let reward_count = rand * (sj / 100)
          let basic_reward = parseInt((reward_count * 30).toString())
          basic_reward = basic_reward + utils.getRandomNumber(1, 9) * 30
          updateParams.basic_reward = basic_reward
        }
      }
      await this.videoRepository.createQueryBuilder(null, queryRunner).update(updateParams).where({ id: video_id }).execute()
      await queryRunner.commitTransaction()
      await queryRunner.release();
      //删除缓存
      await this.redisCacheService.del(`videos:${video_id}:basic`)
    } catch (err) {
      // 有错误做出回滚更改
      await queryRunner.rollbackTransaction()
      await queryRunner.release();
      return err
    }

  }

  questionRewardTitleChange(video_id, question_reward_title) {
    return this.videoRepository.update({ id: video_id }, { question_reward_title: question_reward_title })
  }

  async moveAbroad(video_id: number) {
    let findVideo = await this.videoRepository.findOne({ where: { id: video_id } })
    if (!findVideo) return '未找到视频'
    let findAnswers = await this.answerRepository.find({ where: { video_id: video_id } })
    let findMultiImg = await this.multiImgRespository.find({ where: { video_id: video_id } })
    let db: DataBase = new DataBase()
    let connection = await db.getConnection()
    const queryRunner = connection.createQueryRunner()
    await queryRunner.connect()
    // 开始事务
    await queryRunner.startTransaction()
    try {
      let videoAbroad = new VideoAbroad()
      for (let key in findVideo) {
        videoAbroad[key] = findVideo[key]
      }
      delete videoAbroad.id
      videoAbroad.video_id_old = video_id
      let res = await this.videoAbroadRepository.createQueryBuilder(null, queryRunner).insert().into(VideoAbroad).values(videoAbroad).execute()
      let video_id_new = res.identifiers[0].id
      await this.videoRepository.createQueryBuilder(null, queryRunner).delete().where({ id: video_id }).execute()

      findAnswers.map(e => {
        e.video_id = video_id_new
        delete e.id
      })
      await this.answerAbroadRepository.createQueryBuilder(null, queryRunner).insert().into(AnswerAbroad).values(findAnswers).execute()
      findMultiImg.map(e => {
        e.video_id = video_id_new
        delete e.id
      })
      await this.multiImgAbroadRepository.createQueryBuilder(null, queryRunner).insert().into(MultiImgAbroad).values(findMultiImg).execute()

      await queryRunner.commitTransaction()
      await queryRunner.release();
      //删除缓存
      await this.redisCacheService.del(`videos:${video_id}:basic`)
    } catch (err) {
      // 有错误做出回滚更改
      await queryRunner.rollbackTransaction()
      await queryRunner.release();
      return err
    }
  }
}
